import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag } from 'tdesign-react';
import { AddIcon, EditIcon, DeleteIcon, RefreshIcon } from 'tdesign-icons-react';
import { formatTime } from '../../utils/timeutil';

const { Option } = Select;

export interface BaseTableColumn {
  colKey: string;
  title: string;
  width?: number;
  cell?: (props: { row: any }) => React.ReactNode;
}

export interface BaseTableSearchField {
  key: string;
  type: 'input' | 'select';
  placeholder: string;
  options?: Array<{ value: string; label: string }>;
  width?: number;
}

export interface BaseTablePageProps {
  title: string;
  columns: BaseTableColumn[];
  searchFields?: BaseTableSearchField[];
  fetchData: (params: any) => Promise<{ data: { records: any[]; total: number } }>;
  createItem?: (data: any) => Promise<void>;
  updateItem?: (uuid: string, data: any) => Promise<void>;
  deleteItem?: (uuid: string) => Promise<void>;
  FormComponent: React.ComponentType<any>;
  getRowKey: (row: any) => string;
  getDeleteMessage: (row: any) => string;
}

export default function BaseTablePage({
  title,
  columns,
  searchFields = [],
  fetchData,
  createItem,
  updateItem,
  deleteItem,
  FormComponent,
  getRowKey,
  getDeleteMessage,
}: BaseTablePageProps) {
  const [dataList, setDataList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [editingItem, setEditingItem] = useState<any>();
  const [formTitle, setFormTitle] = useState('新增');
  const [searchValues, setSearchValues] = useState<Record<string, any>>({});
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const getList = async () => {
    setLoading(true);
    try {
      const params = {
        ...searchValues,
        page: pagination.current,
        size: pagination.pageSize,
      };
      const res = await fetchData(params);
      if (res.data?.records) {
        setDataList(res.data.records || []);
        setPagination(prev => ({
          ...prev,
          total: res.data.total || 0,
        }));
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingItem(undefined);
    setFormTitle(`新增${title}`);
    setFormVisible(true);
  };

  const handleEdit = (record: any) => {
    setEditingItem(record);
    setFormTitle(`编辑${title}`);
    setFormVisible(true);
  };

  const handleDelete = (record: any) => {
    if (!deleteItem) return;
    
    const confirmDialog = DialogPlugin.confirm({
      header: '确认删除',
      body: getDeleteMessage(record),
      onConfirm: async () => {
        try {
          await deleteItem(record.uuid);
          MessagePlugin.success('删除成功');
          getList();
        } catch (error) {
          MessagePlugin.error('删除失败');
        }
        confirmDialog.destroy();
      },
    });
  };

  const handleSubmit = async (data: any) => {
    try {
      if (editingItem?.uuid && updateItem) {
        await updateItem(editingItem.uuid, data);
        MessagePlugin.success('更新成功');
      } else if (createItem) {
        await createItem(data);
        MessagePlugin.success('创建成功');
      }
      setFormVisible(false);
      getList();
    } catch (error) {
      MessagePlugin.error(editingItem?.uuid ? '更新失败' : '创建失败');
    }
  };

  const handleSearchChange = (key: string, value: any) => {
    setSearchValues(prev => ({
      ...prev,
      [key]: value,
    }));
  };

  useEffect(() => {
    getList();
  }, [pagination.current, pagination.pageSize, ...Object.values(searchValues)]);

  return (
    <Card title={`${title}管理`}>
      <div style={{ marginBottom: 16 }}>
        {searchFields.length > 0 && (
          <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
            {searchFields.map((field) => (
              <div key={field.key}>
                {field.type === 'input' ? (
                  <Input
                    placeholder={field.placeholder}
                    value={searchValues[field.key] || ''}
                    onChange={(value) => handleSearchChange(field.key, value)}
                    style={{ width: field.width || 150 }}
                  />
                ) : (
                  <Select
                    placeholder={field.placeholder}
                    value={searchValues[field.key]}
                    onChange={(value) => handleSearchChange(field.key, value)}
                    clearable
                    style={{ width: field.width || 120 }}
                  >
                    {field.options?.map((option) => (
                      <Option key={option.value} value={option.value} label={option.label}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                )}
              </div>
            ))}
            <Button theme="primary" onClick={getList}>
              查询
            </Button>
            <Button theme="default" icon={<RefreshIcon />} onClick={getList}>
              刷新
            </Button>
          </div>
        )}
        <div style={{ display: 'flex', gap: 8 }}>
          {createItem && (
            <Button theme="primary" icon={<AddIcon />} onClick={handleCreate}>
              新增{title}
            </Button>
          )}
        </div>
      </div>

      <Table
        data={dataList}
        rowKey={getRowKey}
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showJumper: true,
          onChange: (pageInfo) => {
            setPagination(prev => ({
              ...prev,
              current: pageInfo.current,
              pageSize: pageInfo.pageSize,
            }));
          },
        }}
        columns={[
          ...columns,
          ...(updateItem || deleteItem ? [{
            colKey: 'operation',
            title: '操作',
            width: 150,
            cell: ({ row }: { row: any }) => (
              <div style={{ display: 'flex', gap: 8 }}>
                {updateItem && (
                  <Button
                    theme="primary"
                    variant="text"
                    icon={<EditIcon />}
                    onClick={() => handleEdit(row)}
                  >
                    编辑
                  </Button>
                )}
                {deleteItem && (
                  <Button
                    theme="danger"
                    variant="text"
                    icon={<DeleteIcon />}
                    onClick={() => handleDelete(row)}
                  >
                    删除
                  </Button>
                )}
              </div>
            ),
          }] : []),
        ]}
      />

      <FormComponent
        visible={formVisible}
        onClose={() => setFormVisible(false)}
        onSubmit={handleSubmit}
        initialData={editingItem}
        title={formTitle}
      />
    </Card>
  );
}
